<template>

  <div class="test">
    <div>
      日期选择  <el-date-picker v-model="date" type="month" placeholder="选择日期"  @change="handleDateChange2"></el-date-picker>
      &nbsp;&nbsp; <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                 v-hasPermi="['workOrder:myOrder:add']">报告上传</el-button>
     &nbsp;&nbsp; <el-button type="success" icon="el-icon-s-opportunity" size="mini" @click="openLoginPage">报告设计</el-button>
    </div>
  <el-calendar v-model="value" :first-day-of-week="7">
    <template slot="dateCell" slot-scope="{date, data}" >
      <div  slot="reference" >
        <i v-if="localMonth(data.day)" >{{ Number(data.day.split('-')[2]) }}</i><br/>
        <el-button class="button-text" :title="removeFileExtension(filteredList(data.day,'日报')[0].name)" v-if="localMonth(data.day)&&filteredListIsTrue(data.day,'日报')" type="warning" @click="downloadFile(filteredList(data.day,'日报')[0].url,filteredList(data.day,'日报')[0].name,filteredList(data.day,'日报')[0].id)">
          {{removeFileExtension(filteredList(data.day,'日报')[0].name)}}</el-button>
        <el-button class="button-text" :title="removeFileExtension(filteredList(data.day,'月报')[0].name)" v-if="localMonth(data.day)&&filteredListIsTrue(data.day,'月报')" type="success" @click="downloadFile(filteredList(data.day,'月报')[0].url,filteredList(data.day,'月报')[0].name,filteredList(data.day,'月报')[0].id)">
          {{removeFileExtension(filteredList(data.day,'月报')[0].name)}}</el-button>
<!--        season(data.day)&&end(data.day)&&localMonth(data.day)-->
        <el-button class="button-text" :title="removeFileExtension(filteredList(data.day,'季报')[0].name)" v-if="localMonth(data.day)&&filteredListIsTrue(data.day,'季报')" type="primary" @click="downloadFile(filteredList(data.day,'季报')[0].url,filteredList(data.day,'季报')[0].name,filteredList(data.day,'季报')[0].id)">
          {{removeFileExtension(filteredList(data.day,'季报')[0].name)}}</el-button>
      </div>
    </template>
  </el-calendar>
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="报告文件上传" prop="orderFile">
          <!--           文件列表-->
          <div class="upload-file-list el-upload-list el-upload-list--text">
            <div :key="file.url" class="el-upload-list__item ele-upload-list__item-content"
                 v-for="(file, index) in fileList" style="display: flex;justify-content:  space-between">
              <el-link :underline="false" >
                <span class="el-icon-document" @click="downloadFile(file.url, file.name)"> {{ file.name }} </span>
              </el-link>
              <div class="ele-upload-list__item-content-action">
                <el-link v-if="form.id" :underline="false" @click="handleDeleteFile(file, index)" type="danger">删除</el-link>
                <el-link v-else :underline="false" @click="handleRemoveFile(file, index)" type="danger">删除</el-link>
              </div>
            </div>
          </div>
          <el-upload class="upload-demo" :headers="{Authorization: Authorization}"
                     :action="uploadUrl" :data="{projectCode: currentProject}" name="file"
                     :on-success="handleSuccess" :show-file-list="false" :file-list="fileList">
            <el-button size="small" type="primary">上传报告</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="报告时间" prop="reportTime">
          <el-date-picker clearable  v-model="form.reportTime" type="date"
                          value-format="yyyy-MM-dd" style="width: 100%" placeholder="请选择报告时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="报告类型" prop="reportType">
          <el-select v-model="form.reportType" placeholder="请选择报告类型" class="width_100">
            <el-option v-for="item in reportTypeList"
                       :key="item.key"
                       :value="item.key"
                       :label="item.label">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" >
          上 传
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addReport, delReport, selectReport, selectReportList} from '@/api/report/report';
  import {getToken} from '@/utils/auth';
    export default {
      name: "report",
      props: ['currentProject'],
      data() {
        return {
          value: new Date(),
          year:new Date().getFullYear(),
          month:new Date().getMonth(),
          date:"",
          seasons:[3,6,9,12],
          open:false,
          isHas:false,
          title:"",
          type:"",
          form:{
            projectCode:"",
            reportTime:null,
            reportType:null,
          },
          rules: {
            reportTime: [{
              required: true,
              message: "报告时间不能为空",
              trigger: "blur"
            },
            ],
            reportType: [{
              required: true,
              message: "报告类型不能为空",
              trigger: "change"
            },
            ],
          },
          reportDataList:[],
          reportTypeList:[
            {
              key: '日报',
              label: '日报'
            },
            {
              key: '月报',
              label: '月报'
            },
            {
              key: '季报',
              label: '季报'
            }
          ],
           dictCode: '',
          fileList: [],
          Authorization: 'Bearer ' + getToken(),
          uploadUrl: process.env.VUE_APP_BASE_API + '/common/uploadReportFile',
          //uploadUrl: 'http://127.0.0.1:8081' + '/common/uploadReportFile',
          query:{},
          clickTimes:0,
        }
      },
      watch: {
        value: function() {
          var year = this.value.getFullYear();
          var month = this.value.getMonth() +1;
          var date=this.value.getDate()
          if (date >= 1 && date <= 9) {//日如果小于10就补个0
            date = "0" + date;
          }
          if (month >= 1 && month <= 9) {//月如果小于10就补个0
            month = "0" + month;
          }
          this.year=Number(year);
          this.month=Number(month-1);
          console.log(year + '-' + month + '-' + date) // 打印出日历选中了哪年哪月
        //  this.getCalendarList()   //  调用接口，把拼接好的参数传到后台
          this.selectReportList(year + '-' + month,'日报')
        }
      },
      created() {
        const year = this.value.getFullYear();
        const month = ("0" + (this.value.getMonth() + 1)).slice(-2);
        this.selectReportList(year+"-"+month,'日报')
        console.log(this.currentProject)
        this.$notify({
          title: '操作提示',
          message: this.$createElement('i', { style: 'color: teal'}, '单击可下载报告,双击可删除报告!'),
          position: 'top-right',
          duration: 6000
        })
      },
      methods:{
        openLoginPage() {
          //在线积木报表
          // window.open('http://www.jimureport.com/login', '_blank');
          //本地集成积木报表
          // window.open('http://localhost:9095/jmreport/list', '_blank');
          //服务器部署地址:
          // http://http://139.155.73.171:8081/jmreport/list
          window.open('http://139.155.73.171:8081/jmreport/list', '_blank');
        }
        ,
        downloadFile(url, fileName,id) {
          let _this = this
          _this.clickTimes++;
          if (_this.clickTimes === 2) {
            _this.clickTimes = 0;
            this.$confirm('您要删除该报告吗?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              // delReport(id);
              delReport(id).then(response => {
                if (response.code == 200) {
                  const year = this.value.getFullYear();
                  const month = ("0" + (this.value.getMonth() + 1)).slice(-2);
                  this.selectReportList(year+"-"+month,'日报')
                  this.fileList=[]
                  this.$message({
                    type: 'success',
                    message: '删除成功!'})
                }
              })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              })
              this.$notify({
                title: '操作提示',
                message: this.$createElement('i', { style: 'color: teal'}, '单击可下载报告,双击可删除报告!')
              });
            });
          }
          setTimeout(function () {
            if (_this.clickTimes === 1) {
              _this.clickTimes = 0;
              //  处理单击事件...
          const xhr = new XMLHttpRequest();
          xhr.open('GET', url, true);
          xhr.responseType = 'blob';

          xhr.onload = function() {
            if (xhr.status === 200) {
              const blob = new Blob([xhr.response], { type: 'application/octet-stream' });
              const downloadUrl = URL.createObjectURL(blob);
              const link = document.createElement('a');
              link.href = downloadUrl;
              link.download = fileName;
              link.click();
              URL.revokeObjectURL(downloadUrl);
            }
          };
          xhr.send();
            }
          }, 250)
        },
        filteredList(date,type){
          return this.reportDataList.filter(item => (item.reportTime === date)&&(item.reportType===type));
        },
        filteredListIsTrue(date,type){
          return !(this.reportDataList.filter(item => (item.reportTime === date) && (item.reportType === type)).length === 0);
        },
        selectReportList(date,type){
          this.query.projectCode = this.currentProject;
          // this.query.reportType=type;
          this.query.searchValue=date;
          selectReportList(this.query).then(res=>{
             // console.log
            this.reportDataList=res.data;
             // console.log(this.reportDataList)
          })
        },
        cancel() {
          this.open = false;
          this.reset();
        },
        reset() {
          this.form={}
        },
        handleRemoveFile(file, index) {
          // console.log(file.id)
          this.$modal.confirm('确认删除？').then(res => {
            this.fileList.splice(index, 1);
          })
        },
        /** 新增按钮操作 */
        handleAdd() {
          this.reset();
          this.open = true;
          this.type = 'add';
          this.title = "添加报告";
        },
        //工单附件上传
        handleSuccess(res, file) {
          console.log(res)
          if (res.code == 200) {
            this.fileList.push({
              name: res.originalFilename,
              type: 0,
              url: res.url
            });
          }else {
            this.$message.warning(res.msg);
          }
        },
        /** 提交按钮 */
        submitForm() {
          if (this.fileList.length>0){
            this.$refs["form"].validate(valid => {
              if (valid) {
                this.form.projectCode = this.currentProject;
                this.form.url = this.fileList[0].url;
                this.form.name = this.fileList[0].name;
                this.form.type = this.fileList[0].type;
                console.log(this.form)
                addReport(this.form).then(response => {
                  this.$modal.msgSuccess("报告上传成功");
                  this.open = false;
                  const year = this.value.getFullYear();
                  const month = ("0" + (this.value.getMonth() + 1)).slice(-2);
                  this.selectReportList(year+"-"+month,'日报')
                  this.fileList=[]
                });
              }
            });
          }else {
            this.$modal.msgError("请上传报告");
          }

        },
        getCalendarList(){
          console.log('接口调用成功');
        },
        handleDateChange2(){
          if (this.date){
            this.value=this.date
          }

        },
        removeFileExtension(filename) {
          const lastDotIndex = filename.lastIndexOf(".");
          if (lastDotIndex > 0) {
            return filename.substring(0, lastDotIndex);
          } else {
            return filename;
          }
          },
        localMonth(now){
          let month = now.split("-")[1];
          let year = now.split("-")[0];
          let month1 = this.month+1;
          return Number(month)==month1&&year==this.year;

        },
        end(now) {
          let year = now.split("-")[0];
          let month = now.split("-")[1];
          let day = now.split("-")[2];
          const lastDay = new Date(year, (Number(month)), 0).getDate();
          return day==lastDay;
        },
        season(now) {
          let month = now.split("-")[1];
          for (const s of this.seasons) {
            if (s==Number(month)){
              return true
            }
          }

          return false;
        },
        handleDateChange(date) {
          const year = date.getFullYear();
          const month = date.getMonth() + 1;
          const header = `${year}年${month}月`;
          document.querySelector('.custom-header').textContent = header;
        }
      },



    }
</script>

<style scoped>
  .is-selected {
    color: #1989FA;
  }

  .test /deep/  .el-calendar-table .el-calendar-day  {
    height: 140px;
  }
   .el-calendar-table /deep/ td.is-disabled {
    display: none;
  }
  .disabled-date {
    color: #ccc;
    pointer-events: none;
  }
  .el-button {
    margin-left: unset;
  }
  .el-button + .el-button {
    margin-left: unset;
  }
  .button-text {
    overflow: hidden;
    text-overflow: ellipsis;
    word-break: break-all;
    white-space: nowrap;
    max-width: 100%;
  }
  .el-calendar-day i {
    display: inline-block;
    text-align: center;
    width: 100%;
  }

</style>
